{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 1. 以Lena为原始图像，通过OpenCV实现平均滤波，高斯滤波及中值滤波，比较滤波结果。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "#-*-coding:utf-8-*-\n",
    "\n",
    "import cv2 as cv\n",
    "import numpy as np\n",
    "\n",
    "filename = 'lena.jpg'\n",
    "img = cv.imread(filename)\n",
    "gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n",
    "\n",
    "## 平均滤波\n",
    "ave = cv.blur(gray, (5, 5))\n",
    "\n",
    "## 高斯滤波\n",
    "gaussi = cv.GaussianBlur(ave, (5, 5), 0)\n",
    "\n",
    "## 中值滤波\n",
    "media = cv.medianBlur(gray, 5)\n",
    "\n",
    "cv.imshow(\"ave\", ave);\n",
    "cv.imshow(\"gaussi\", gaussi);\n",
    "cv.imshow(\"media\", media);\n",
    "\n",
    "cv.waitKey()\n",
    "cv.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 图像比较见home_work(senior).docx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 2. 以Lena为原始图像，通过OpenCV使用Sobel及Canny算子检测，比较边缘检测结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "#-*-coding:utf-8-*-\n",
    "\n",
    "import cv2 as cv\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "\n",
    "filename = r'E:\\develop_software\\AI\\resource\\lena.jpg'\n",
    "img = cv.imread(filename, 0)\n",
    "\n",
    "sobelx = cv.Sobel(img, cv.CV_64F, 1, 0, ksize=5)\n",
    "sobely = cv.Sobel(img, cv.CV_64F, 0, 1, ksize=5)\n",
    "edges = cv.Canny(img, 100, 200)\n",
    "\n",
    "\n",
    "plt.subplot(2,2,1),plt.imshow(img,cmap = 'gray')\n",
    "plt.title('Original Image'), plt.xticks([]), plt.yticks([])\n",
    "\n",
    "plt.subplot(2,2,2),plt.imshow(edges,cmap = 'gray')\n",
    "plt.title(\"Canny\"), plt.xticks([]), plt.yticks([])\n",
    "\n",
    "plt.subplot(2,2,3),plt.imshow(sobelx,cmap = 'gray')\n",
    "plt.title('Sobel X'), plt.xticks([]), plt.yticks([])\n",
    "\n",
    "plt.subplot(2,2,4),plt.imshow(sobely,cmap = 'gray')\n",
    "plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 图像比较见home_work(senior).docx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 3.在OpenCV安装目录下找到课程对应演示图片(安装目录\\sources\\samples\\data)，首先计算灰度直方图，进一步使用大津算法进行分割，并比较分析分割结果。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "#-*-coding:utf-8-*-\n",
    "\n",
    "import cv2 as cv\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "filename = 'rice.png'\n",
    "gray = cv.imread(filename, 0)\n",
    "cv.imshow(\"gray\", gray)\n",
    "\n",
    "hist = cv.calcHist([gray], [0], None, [256], [0, 256])\n",
    "plt.figure()\n",
    "plt.title(\"Grayscale Histogram\")\n",
    "plt.xlabel(\"Bins\")\n",
    "plt.ylabel(\"# of Pixels\")\n",
    "plt.plot(hist)\n",
    "plt.xlim([0, 256])\n",
    "plt.show()\n",
    "\n",
    "## 大津算法分割\n",
    "_, th_hold = cv.threshold(gray, 125, 255, 0)\n",
    "cv.imshow(\"th_hold\", th_hold)\n",
    "\n",
    "cv.waitKey()\n",
    "cv.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 图像比较,大津算法分割结果见home_work(senior).docx,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 4.使用米粒图像，分割得到各米粒，首先计算各区域(米粒)的面积、长度等信息，进一步计算面积、长度的均值及方差，分析落在3sigma范围内米粒的数量。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "#-*-coding:utf-8-*-\n",
    "import cv2 as cv\n",
    "import copy\n",
    "\n",
    "filename = r'E:\\develop_software\\AI\\resource\\rice.png'\n",
    "img = cv.imread(filename)\n",
    "gray = cv.imread(filename, 0)\n",
    "\n",
    "\n",
    "_, bw = cv.threshold(gray, 0, 0xff, cv.THRESH_OTSU)\n",
    "element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))\n",
    "bw = cv.morphologyEx(bw, cv.MORPH_OPEN, element)\n",
    "\n",
    "seg = copy.deepcopy(bw)\n",
    "cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n",
    "count = 0\n",
    "for i in range(len(cnts), 0, -1):\n",
    "    c = cnts[i-1]\n",
    "    area = cv.contourArea(c)\n",
    "    if area < 10:\n",
    "        continue\n",
    "    count = count +1\n",
    "    print(\"blob\", i, \": \", area)\n",
    "\n",
    "    x, y, w, h = cv.boundingRect(c)\n",
    "    cv.rectangle(img, (x, y), (x+w, y+h), (0, 0, 0xff), 1)\n",
    "    cv.putText(img, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))\n",
    "\n",
    "print(\"rice_count: \", count)\n",
    "cv.imshow(\"orign:\", img)\n",
    "cv.imshow(\"hisogram\", bw)\n",
    "\n",
    "cv.waitKey()\n",
    "cv.destroyAllWindows()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## rice_count = 102\n",
    "## 图像见home_work(senior).docx,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "##5. 使用棋盘格及自选风景图像，分别使用SIFT、FAST及ORB算子检测角点，并比较分析检测结果。 (可选)使用Harris角点检测算子检测棋盘格，并与上述结果比较。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 使用棋盘格进行角点检测运算,代码如下:\n",
    "import cv2\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import copy\n",
    "\n",
    "filename = 'chessboard.png'\n",
    "dst = 'result.png'\n",
    "\n",
    "\n",
    "def resizeImage(file_in, file_out, height, width):\n",
    "    image = Image.open(file_in)\n",
    "    resize_image = image.resize((width, height), Image.ANTIALIAS)\n",
    "    resize_image.save(file_out)\n",
    "\n",
    "\n",
    "resizeImage(filename, dst, 256, 512)\n",
    "dst_img = cv2.imread(dst)\n",
    "gray = cv2.cvtColor(dst_img, cv2.COLOR_BGR2GRAY)\n",
    "img = copy.deepcopy(gray)\n",
    "## 使用sift校测角点\n",
    "sift = cv2.xfeatures2d.SIFT_create()\n",
    "kp = sift.detect(gray, None)\n",
    "img = cv2.drawKeypoints(gray, kp, img)\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.waitKey()\n",
    "cv2.destroyAllWindows()\n",
    "\n",
    "##  使用fast算子检测角点\n",
    "\n",
    "import numpy as np\n",
    "import cv2\n",
    "from matplotlib import pyplot as plt\n",
    "import copy\n",
    "from PIL import Image\n",
    "\n",
    "\n",
    "def resizeImage(file_in, file_out, height, width):\n",
    "    image = Image.open(file_in)\n",
    "    resize_image = image.resize((width, height), Image.ANTIALIAS)\n",
    "    resize_image.save(file_out)\n",
    "\n",
    "\n",
    "filname = r'E:\\develop_software\\AI\\resource\\chessboard.png'\n",
    "img = cv2.imread(filname)\n",
    "gray = cv2.imread(filname, 0)\n",
    "\n",
    "dst = 'result.png'\n",
    "resizeImage(filname, dst, 256, 512)\n",
    "dst_img = cv2.imread(dst)\n",
    "img2 =copy.deepcopy(dst_img)\n",
    "\n",
    "\n",
    "fast=cv2.FastFeatureDetector_create(threshold=20, nonmaxSuppression=True, type=cv2.FAST_FEATURE_DETECTOR_TYPE_9_16)#获取FAST角点探测器\n",
    "\n",
    "# find and draw the keypoints\n",
    "kp = fast.detect(img2, None)\n",
    "img2 = cv2.drawKeypoints(dst_img, kp, img2, color=(255, 0, 0))\n",
    "\n",
    "# Print all default params\n",
    "print(\"Threshold: \", fast.getThreshold())\n",
    "print(\"nonmaxSuppression: \", fast.getNonmaxSuppression())\n",
    "print(\"Total Keypoints with nonmaxSuppression: \", len(kp))\n",
    "\n",
    "cv2.imshow(\"fast_true.png\", img2)\n",
    "\n",
    "cv2.waitKey()\n",
    "cv2.destroyAllWindows()\n",
    "##################################################################################################\n",
    "############################  使用ORB算子检测角点   ##############################################\n",
    "##################################################################################################\n",
    "\n",
    "import numpy as np\n",
    "import cv2\n",
    "from matplotlib import pyplot as plt\n",
    "import copy\n",
    "from PIL import Image\n",
    "\n",
    "\n",
    "def resizeImage(file_in, file_out, height, width):\n",
    "    image = Image.open(file_in)\n",
    "    resize_image = image.resize((width, height), Image.ANTIALIAS)\n",
    "    resize_image.save(file_out)\n",
    "\n",
    "\n",
    "filname = r'E:\\develop_software\\AI\\resource\\chessboard.png'\n",
    "img = cv2.imread(filname)\n",
    "gray = cv2.imread(filname, 0)\n",
    "\n",
    "dst = 'result.png'\n",
    "resizeImage(filname, dst, 256, 512)\n",
    "dst_img = cv2.imread(dst)\n",
    "img2 =copy.deepcopy(dst_img)\n",
    "\n",
    "orb = cv2.ORB_create()\n",
    "kp = orb.detect(dst_img,None)\n",
    "kp, des = orb.compute(dst_img, kp)\n",
    "img2 = cv2.drawKeypoints(dst_img, kp, img2, color=(0, 255, 0), flags=0)\n",
    "plt.imshow(img2), plt.show()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
